import networkx as nx
from scipy import sparse

from EmpVoting import NetworkModifier

class AgentUtilGlobalAlg(NetworkModifier):

    def __init__(self, useDynamicFields = False):
        '''
        Constructor
        '''
        self.useDynamicFields = useDynamicFields
        
        
    def Apply(self, network):
        numAgents = len(network.agentList)
        
        #adjacencyMatrix
        M = nx.to_scipy_sparse_matrix(network.graph)
        #selfLoopMatrix
        D = sparse.tril(M) - sparse.tril(M, -1)
        I = sparse.identity(numAgents)
        
        utilMultiplier = (I - M + D).todense().I * D
        
        networkOrderedNodes = network.graph.nodes()
        
        for alternative in network.alternativeSet:
            agentIndex = 0
            for agent in networkOrderedNodes:
                agentUtil = 0
                for i in range(0, numAgents):
                    agentUtil += utilMultiplier[agentIndex, i] * networkOrderedNodes[i].intrinsicUtilDict[alternative]
                
                self.SetAgentDictEntry(agent, "overallUtilDict", alternative, agentUtil)
                
                agentIndex += 1